package com.sh.data.engine.domain.datadev.offline.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.data.engine.domain.datadev.offline.service.DatadevResourceService;
import com.sh.data.engine.repository.dao.datadev.DatadevResourceMapper;
import com.sh.data.engine.repository.dao.datadev.entity.DatadevResourceEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
public class DatadevResourceServiceImpl
    extends ServiceImpl<DatadevResourceMapper, DatadevResourceEntity>
    implements DatadevResourceService {

    @Override
    public List<DatadevResourceEntity> getResourceByNodeId(Long nodeId) {

        List<DatadevResourceEntity> list =
            list(
                new LambdaQueryWrapper<DatadevResourceEntity>()
                    .eq(DatadevResourceEntity::getNodeId, nodeId));
        return list;
    }

    @Override
    public DatadevResourceEntity getResourceIsActiveByNodeId(Long nodeId) {
        DatadevResourceEntity res =
            getOne(
                new LambdaQueryWrapper<DatadevResourceEntity>()
                    .eq(DatadevResourceEntity::getNodeId, nodeId)
                    .eq(DatadevResourceEntity::getIsActive, 1));
        return res;
    }

    @Override
    public DatadevResourceEntity findByProjectIdAndName(Long projectId, String name) {
        if (Objects.isNull(projectId) || StringUtils.isBlank(name)) {
            return null;
        }

        LambdaQueryWrapper<DatadevResourceEntity> eq =
            new LambdaQueryWrapper<DatadevResourceEntity>()
                .eq(DatadevResourceEntity::getProjectId, projectId)
                .eq(DatadevResourceEntity::getFileName, name)
                .orderByDesc(DatadevResourceEntity::getId);

        List<DatadevResourceEntity> list = this.list(eq);

        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
}
